package com.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.reggie.common.R;
import com.reggie.dto.DishDto;
import com.reggie.entity.category;
import com.reggie.entity.dish;
import com.reggie.entity.dishFlavor;
import com.reggie.mapper.dishMapper;
import com.reggie.service.categoryService;
import com.reggie.service.dishFlavorService;
import com.reggie.service.dishService;
import com.reggie.vo.dishVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Service
@Transactional//开启事务管理
@Slf4j
public class dishServiceImpl extends ServiceImpl<dishMapper, dish> implements dishService {
    @Autowired
    private dishFlavorService dishFlavorService;

    @Autowired
    private categoryService categoryService;

    @Override
    public void saveDto(DishDto dto) {
        this.save(dto);//因为在插入数据库前会给id字段赋值
        Long id = dto.getId();//获取id
        List<dishFlavor> flavors = dto.getFlavors();
        flavors.forEach(t -> t.setDishId(id));
        dishFlavorService.saveBatch(flavors);
    }


    @Override
    public R<Page> SelectDishForCategoryName(int page, int pageSize, String name, HttpSession session) {
        log.info("{}:进行了查询", session.getAttribute("employee"));
        Page<dish> pageInfo = new Page<>(page, pageSize);
        Page<dishVo> dishVoPage = new Page<>();
        LambdaQueryWrapper<dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(name != null, dish::getName, name);
        queryWrapper.orderByDesc(dish::getUpdateTime);
        this.page(pageInfo, queryWrapper);
        //将pageInfo拷贝到dishVoPage上
        BeanUtils.copyProperties(pageInfo, dishVoPage, "records");
        List<dish> DishRecords = pageInfo.getRecords();
        List<dishVo> DishVoRecords = new ArrayList<>();
        DishRecords.forEach(dish -> {
            dishVo dishVo = new dishVo();
            BeanUtils.copyProperties(dish, dishVo);
            category category = categoryService.getById(dish.getCategoryId());
            dishVo.setCategoryName(category.getName());
            DishVoRecords.add(dishVo);
        });
        dishVoPage.setRecords(DishVoRecords);
        return R.success(dishVoPage);
    }
}
